package com.nightpiter.view.drawer.rapid;

import java.util.ArrayList;
import java.util.HashMap;

import com.nightpiter.model.MetroModelData;
import com.nightpiter.model.objects.Hub;
import com.nightpiter.model.objects.Station;
import com.nightpiter.model.objects.Transfer;
import com.nightpiter.model.objects.Transition;
import com.nightpiter.model.objects.Tunnel;
import com.nightpiter.view.Calculator.Mode;
import com.nightpiter.view.drawer.rapid.Temp.Component;
import com.nightpiter.view.graphics.PointF;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
class Structure {

	private HashMap<Station, Node> nodesMap;

	private HashMap<Transition, Link> linksMap;

	private MetroModelData modelData;

	private Mode mode;

	public Structure(MetroModelData modelData, Mode mode) {
		this.modelData = modelData;
		this.mode = mode;
		nodesMap = new HashMap<Station, Node>(modelData.getStations()
				.size(), 1);
		linksMap = new HashMap<Transition, Link>(modelData.getTransfers()
				.size()
				+ modelData.getTunnels().size(), 1);

		initNodes();

		initLinks();

	}

	private void initNodes() {
		for (Hub hub : modelData.getHubs()) {
			ArrayList<Component> components = Temp.Knot.untie(hub, mode);
			for (Temp.Component component : components) {
				Node node = new Node(component.getStations(),
						component.getCoordF());
				for (Station station : component.getStations()) {
					nodesMap.put(station, node);
				}
			}
		}

		for (Station station : modelData.getStations()) {
			if (station.getHub() == null) {
				nodesMap.put(station, new Node(station, new PointF(
						station, mode)));
			}
		}

	}

	private void initLinks() {
		for (Tunnel tunnel : modelData.getTunnels()) {
			Node fromNode = nodesMap.get(tunnel.getFromStation());
			Node toNode = nodesMap.get(tunnel.getToStation());
			Link link = fromNode.searchNeighbor(toNode);
			link.addTransition(tunnel);
			linksMap.put(tunnel, link);
		}

		for (Transfer transfer : modelData.getTransfers()) {
			Node fromNode = nodesMap.get(transfer.getFromStation());
			Node toNode = nodesMap.get(transfer.getToStation());
			Link link = fromNode.searchNeighbor(toNode);
			link.addTransition(transfer);
			linksMap.put(transfer, link);
		}

	}

	public boolean process(Station station) {
		Node node = nodesMap.get(station);
		if (node == null) {
			nodesMap.put(station, new Node(station, new PointF(station,
					mode)));
		} else {
			Hub hub = station.getHub();
			if (hub == null) {
				node.getCoordF().set(station, mode);
			} else {
				// can not do anything..
				return false;
			}
		}
		return true;
	}

	public HashMap<Station, Node> getNodesMap() {
		return nodesMap;
	}

	public HashMap<Transition, Link> getLinksMap() {
		return linksMap;
	}

}
